<template>
  <Layout>
    <div ref="blogRef" v-loading="loading" class="main-container">
      <BlogDetail v-if="data" :blog="data"></BlogDetail>
      <BlogComment v-if="!loading"></BlogComment>
    </div>
    <template #right>
      <div v-loading="loading" class="right-container">
        <BlogToc v-if="data" :toc="data.toc"></BlogToc>
      </div>
    </template>
  </Layout>
</template>
<script lang="ts" setup>
import { getBlog } from '@/api/blog'
import Layout from '@/components/Layout/index.vue'
import { useFetchData } from '@/hooks/useFetchData'
import { useRoute } from 'vue-router'
import BlogDetail from './components/BlogDetail.vue'
import BlogToc from './components/BlogToc.vue'
import BlogComment from './components/BlogComment.vue'
import { onMounted, ref } from 'vue'
import { useMainScroll } from '@/hooks/useMainScroll'
import type { Ref } from 'vue-demi'

const blogRef = ref<HTMLDivElement | null>(null)

const route: any = useRoute()

const fetchData = () => {
  return getBlog(route.params.id).then((res) => res.data)
}

const { data, loading } = useFetchData<any>({
  defaultValue: null,
  fetchData
})

const initScrollToHash = () => {
  // 初始化定位
  const hash = location.hash
  location.hash = ''
  setTimeout(() => {
    location.hash = hash
  }, 800)
}

useMainScroll(blogRef as Ref<HTMLDivElement>)

onMounted(() => {
  // 初始化定位
  initScrollToHash()
})
</script>
<style lang="less" scoped>
.main-container {
  overflow-y: scroll;
  height: 100%;
  box-sizing: border-box;
  padding: 20px;
  position: relative;
  width: 100%;
  overflow-x: hidden;
  scroll-behavior: smooth;
}

.right-container {
  width: 300px;
  height: 100%;
  overflow-y: scroll;
  box-sizing: border-box;
  position: relative;
  padding: 20px;
}
</style>